package com.lyy.consolidate.homework9;


/**
 * @Author: GZQ
 * @date: 2024/12/22 17:00
 * @description: 巩固练习8
 */

public class HomeWork09 {

    public static void main(String[] args) {
        // 测试学生
        Student student = new Student("jack", '男', 18, "10001");
        student.printInfo(); // 封装
        // 测试老师
        Teacher teacher = new Teacher("tom", '男', 18, 10);
        System.out.println("----------------------------");
        teacher.printInfo();

        // 定义多态数组, 里面保存2个学生和2个老师, 要求按照年龄从高到低排序
        Person[] persons = new Person[4];
        persons[0] = new Student("jack", '男', 18, "10001");
        persons[1] = new Student("mary", '女', 19, "10002");
        persons[2] = new Teacher("scott", '男', 38, 10);
        persons[3] = new Teacher("kate", '女', 28, 7);

        // 创建对象
        HomeWork09 homeWork09 = new HomeWork09();
        homeWork09.bubbleSort(persons);

        // 输出排序后的数组
        System.out.println("----排序后的数组情况-----");
        for (int i = 0; i < persons.length; i++) {
            System.out.println(persons[i]);
        }

        // 遍历数组, 调用test 方法
        System.out.println("====================");
        for (int i = 0; i < persons.length; i++) { // 遍历多态数组
            homeWork09.test(persons[i]);
        }
    }

    // 定义方法, 形参为Person类型, 功能：调用学生的study或教师的teach方法
    // 分析这里会使用到向下转型和类型判断
    public void test(Person p) {
        if (p instanceof Student) { //p 的运行类型如果是Student
            ((Student) p).study();
        } else if (p instanceof Teacher) {
            ((Teacher) p).teach();
        } else {
            System.out.println("do nothing...");
        }
    }

    // 定义方法,完成年龄从高到底排序
    public void bubbleSort(Person[] persons) {
        Person temp = null;
        for (int i = 0; i < persons.length - 1; i++) {
            for (int j = 0; j < persons.length - 1 - i; j++) {
                // 判断条件, 这里条件可以根据需要, 变化
                if(persons[j].getAge() < persons[j + 1].getAge()) {
                    temp = persons[j];
                    persons[j] = persons[j + 1];
                    persons[j + 1] = temp;
                }
            }
        }
    }
}
